<template>
  <div class="single"/>
</template>

<script>
import {
  getSingleProductSale
} from '@/api/echart'
import * as echarts from 'echarts'

export default {
  name: 'single',
  data() {
    return {
      singleData: [],
      nameData: [],
      valueData: [],
      start: 0,
      end: 5,
      timeId: '',
      colorFul: ['#6A5ACD', '#FF1493', '#FFB6C1', '#00FFFF', '#00FF7F',
        '#FFFF00', '#FFA500', '#FF7F50', '#FF6347', '#FF0000']
    }
  },
  mounted() {
    this.getSingleData()
  },
  methods: {
    // 获取单品销量冠军
    getSingleData() {
      getSingleProductSale().then(res => {
        this.singleData = res.data
        this.setChart()
        this.setTime()
      })
    },
    // 分出名字和销量
    extractValue() {
      this.nameData = this.singleData.map(i => {
        return i.name
      })
      this.valueData = this.singleData.map((i, index) => {
        return {
          value: i.payments,
          itemStyle: {
            color: this.colorFul[index]
          }
        }
      })
    },
    // 设置柱状图
    setChart() {
      this.extractValue()
      const nameArr = this.nameData.splice(this.start, this.end)
      const valueArr = this.valueData.splice(this.start, this.end)

      const chartDom = document.querySelector('.right_box')
      const myChart = echarts.init(chartDom)
      const option = {
        title: {
          text: '单品销售榜',
          left: 'center',
          top: '5%'
        },
        grid: {
          left: '22%',
          top: '18%'
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: nameArr
        },
        series: [{
          data: valueArr,
          type: 'bar',
          label: {
            normal: {
              show: true,
              position: 'right'
            }
          }
        }]
      }
      myChart.setOption(option)
    },

    // 设置定时器
    setTime() {
      if (this.timeId) {
        clearInterval(this.timeId)
      }
      this.timeId = setInterval(() => {
        if (this.end === this.singleData.length) {
          this.start = 0
          this.end = 5
        } else {
          this.start = 5
          this.end = 10
        }
        this.setChart()
      }, 5000)
    }
  },
  beforeDestroy() {
    clearInterval(this.timeId)
  }

}
</script>

<style>
</style>
